package household.household.dao;

import household.base.IBaseDAOImpl;
import household.household.model.SettleHousehold;
import household.util.FlexigridForm;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

@Service("settleHouseholdDAO")
public class SettleHouseholdDAOImpl extends IBaseDAOImpl<SettleHousehold> implements SettleHouseholdDAO {

	@SuppressWarnings("unchecked")
	public List<SettleHousehold> queryByName(String name) {
		return this.getCurrentSession().createQuery("from SettleHousehold where name=:name").setParameter("name", name).list();
	}

	@SuppressWarnings("unchecked")
	public List<SettleHousehold> queryAll() {
		return this.getCurrentSession().createQuery("from SettleHousehold").list();
	}

	@SuppressWarnings("unchecked")
	public List<SettleHousehold> queryFromFlexigrid(FlexigridForm flexigridForm) {
		Criteria criteria = this.getCurrentSession().createCriteria(SettleHousehold.class);
		criteria.add(Restrictions.like(flexigridForm.getQtype(), "%"+flexigridForm.getQuery()+"%"));
		long count = (long) criteria.setProjection(Projections.rowCount()).uniqueResult();
		flexigridForm.setTotal(count);
		criteria.setProjection(null);
		criteria.setFirstResult((flexigridForm.getPage()-1)*flexigridForm.getRp())
		.setMaxResults(flexigridForm.getRp());
		if(flexigridForm.getSortorder().equals("asc")){
			criteria.addOrder(Order.asc(flexigridForm.getSortname()));
		}else if(flexigridForm.getSortorder().equals("desc")){
			criteria.addOrder(Order.desc(flexigridForm.getSortname()));
		}
		return criteria.list();
	}	
}
